(function($){
  var viewer = new Cesium.Viewer('cesium-viewer',{
    animation: false,
    baseLayerPicker: false,
    timeline: false,
    vrButton: false,
    geocoder: false,
    homeButton: false,
    sceneModePicker: false,
    selectionIndicator: false,
    navigationHelpButton: false,
    fullscreenButton: false,
    creditsDisplay: false,
    baseLayerPicker: false,
    imageryProvider: false
  })
  var tileset = null
  viewer.scene.debugShowFramesPerSecond = true
viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
    url: 'http://t0.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=827222731593c05f3befc079a43e106a',
    layer: 'tdtBasicLayer',
    style: 'default',
    format: 'image/jpeg',
    tileMatrixSetID: 'GoogleMapsCompatible',
    proxy: new Cesium.DefaultProxy('/proxy/')
  }))

  viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
    url: 'http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=827222731593c05f3befc079a43e106a',
    layer: 'tdtSATAnnoLayer',
    style: 'default',
    format: 'image/jpeg',
    tileMatrixSetID: 'GoogleMapsCompatible',
    proxy: new Cesium.DefaultProxy('/proxy/')
  }))

//   viewer.imageryLayers.addImageryProvider(new Cesium.SingleTileImageryProvider({
//     url : '../img/pizhou.png',
//     rectangle : Cesium.Rectangle.fromDegrees(117.94180706409335,34.394752765255, 117.95974268717369, 34.40436215441455)
// }))

  // 加载3d图层
  $('#loadMapBtn').on('click', function(){
    var mapUrl = $('#mapUrl').val().trim()
    if(mapUrl === '') {
        alert('请输入三维图层地址')
        return
    }
    if(mapUrl.indexOf('http') === -1) {
        alert('请输入正确三维图层地址')
        return
    }
    if(tileset) {
        viewer.scene.primitives.remove(tileset)
        tileset = null
    }
    // 添加3d瓦片
    tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
        url: mapUrl,
        maximumScreenSpaceError: 5, // 默认为16，值越小模型越精细，性能越差，根据项目实际情况进行调整
        maximumMemoryUsage:1024, // GPU使用内存 默认512
    }))
     
    // 调整视角到瓦片
    viewer.flyTo(tileset)
  })

  $('#getCameraBtn').on('click', function(){
    $('#cameraInput').val(
        'destination'+ viewer.camera.positionWC.toString() + ',\n' +
        'heading:'+Cesium.Math.toDegrees(viewer.camera.heading).toFixed(4) + ',\n'+
        'pitch:'+Cesium.Math.toDegrees(viewer.camera.pitch).toFixed(4) + ',\n'+
        'roll:'+Cesium.Math.toDegrees(viewer.camera.roll).toFixed(4) + ',\n'
    )
  })

  // 定位坐标
  $('#locationBtn').on('click', function(){
    var location = $('#locationInput').val().trim()
    if(location === '') {
        alert('请输入定位坐标')
        return
    }
    if(location.indexOf(',') === -1) {
        alert('请输入正确坐标格式')
        return
    }
    var ll = location.split(',')
  viewer.entities.removeAll()
  viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(ll[1],ll[0]),
    point : {
      pixelSize : 5,
      color : Cesium.Color.RED,
      outlineColor : Cesium.Color.WHITE,
      outlineWidth : 2
    },
    label : {
      text : location,
      font : '14pt monospace',
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      outlineWidth : 2,
      verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
      pixelOffset : new Cesium.Cartesian2(0, -9)
    }
  })
    viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(ll[1],ll[0],600)
    })
  })

    // 定位位置
    $('#positonBtn').on('click', function(){
        var keyWord = $('#positonInput').val().trim()
        if(keyWord === '') {
            alert('请输入位置关键字')
            return
        }
        $.get('http://api.tianditu.gov.cn/geocoder?ds={"keyWord":"'+keyWord+'"}&tk=827222731593c05f3befc079a43e106a', function(data){
            var location = JSON.parse(data).location
            if(location) {
              viewer.entities.removeAll()
              viewer.entities.add({
                position: Cesium.Cartesian3.fromDegrees(location.lon,location.lat),
                point : {
                  pixelSize : 5,
                  color : Cesium.Color.RED,
                  outlineColor : Cesium.Color.WHITE,
                  outlineWidth : 2
                },
                label : {
                  text : keyWord,
                  font : '14pt monospace',
                  style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                  outlineWidth : 2,
                  verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
                  pixelOffset : new Cesium.Cartesian2(0, -9)
                }
              })
                viewer.camera.flyTo({
                    destination: Cesium.Cartesian3.fromDegrees(location.lon,location.lat,600)
                })
            }
        })
    
      })

  var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  handler.setInputAction(function(e){
    // let pos = viewer.scene.pickPosition(e.position)
    // let ll = Cesium.Cartographic.fromCartesian(pos)
    // const lat = Cesium.Math.toDegrees(ll.latitude)
    // const lng = Cesium.Math.toDegrees(ll.longitude)
    // console.log(pos.toString())
    //拾取笛卡尔坐标
    var ellipsoid = viewer.scene.globe.ellipsoid;//全局椭球体
    var cartesian = viewer.scene.camera.pickEllipsoid(e.position, ellipsoid)//拾取鼠标在椭圆上的结束点笛卡尔坐标点
    if (cartesian) {
        //转化笛卡尔坐标 为经纬度
        var cartographic = ellipsoid.cartesianToCartographic(cartesian);//笛卡尔坐标转制图坐标
        const lng = Cesium.Math.toDegrees(cartographic.longitude).toFixed(7)
        const lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(7)
        $('#latlngInput').val(lng + ',' + lat)
        $('#cartesianInput').val(cartographic.toString())
        console.log(lat+','+lng)
    }
    // $('#latlngInput').val(lat+','+lng)
    // $('#cartesianInput').val(pos.toString())
  },Cesium.ScreenSpaceEventType.LEFT_CLICK)

  var $pointer = $('#pointer')
  var degree = Cesium.Math.toDegrees(viewer.scene.camera.heading)
  $pointer.css('transform', 'rotate('+degree+'deg)')
  viewer.scene.postRender.addEventListener(scene => {
      var degree = Cesium.Math.toDegrees(scene.camera.heading)
      $pointer.css('transform', 'rotate('+degree+'deg)')
  })
})(jQuery)